/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package users;

import catalog.CD;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.util.HashSet;
import java.util.List;

/**
 *
 * @author smoniz
 */
public class UsersFromXMLHandler {

    public static void main(String[] args) {

        Document xml = catalog.XMLParser.parseXmlFile("./dat/users.xml");
       List<User> users = parseDoc(xml);

  for (User user : users) {
           System.out.println(user);
        }



    }

    public static void getUsers() {

        Document xml = catalog.XMLParser.parseXmlFile("./dat/users.xml");
        List<User> users = parseDoc(xml);
        for (User user : users) {
            Users.addUser(user);
        }

    }

    private static List<User> parseDoc(Document doc) {
        Element docElement = doc.getDocumentElement();
        ArrayList<User> users = new ArrayList<User>();
        NodeList nl = docElement.getElementsByTagName("user");
        if (nl != null && nl.getLength() > 0) {
            for (int i = 0; i < nl.getLength(); i++) {
                User user = userFromXML((Element) nl.item(i));
                users.add(user);


            }



        }


        return users;
    }

    private static User userFromXML(Element e) {
        String username = CD.getTextValue(e, "username");
        String password = CD.getTextValue(e, "password");
        String name = CD.getTextValue(e, "name");
        String address = CD.getTextValue(e, "address");
        String phone = CD.getTextValue(e, "phone");
        String[] wlist = CD.getTextValue(e, "wishlist").split(",");
        User user = new User(username, password, name, address, phone);
        for (String w : wlist) {
            List<CD> cds = catalog.Catalog.getCat().searchtitle(w);
            user.addCDs(cds);


        }
        return user;

    }
}
